from django.http import JsonResponse
from .exception_enum import StatusCodeEnum

class R:
    """统一响应类"""
    def __init__(self):
        self.code = None
        self.message = None
        self._data = {}

    @staticmethod
    def ok(data=None):
        r = R()
        r.code = StatusCodeEnum.OK.code
        r.message = StatusCodeEnum.OK.message
        if data is not None:
            r._data = data
        return r.to_dict()

    @staticmethod
    def error(message=None, code=None):
        r = R()
        r.code = code or StatusCodeEnum.ERROR.code
        r.message = message or StatusCodeEnum.ERROR.message
        return r.to_dict()

    @staticmethod
    def from_enum(enum):
        r = R()
        r.code = enum.code
        r.message = enum.message
        return r.to_dict()

    def to_dict(self):
        return {
            'code': self.code,
            'message': self.message,
            'data': self._data
        }

# 兼容旧版的快捷方法
def json_response_success(data=None):
    return JsonResponse(R.ok(data))

def json_response_error(message='error', code=400, data=None):
    return JsonResponse(R.error(message, code))

def json_response_not_found(message='资源不存在'):
    return JsonResponse(R.error(message, StatusCodeEnum.NODATA_ERR.code))

def json_response_server_error(message='服务器错误'):
    return JsonResponse(R.error(message, StatusCodeEnum.SERVER_ERR.code))

def json_response_unauthorized(message='未授权', code=401, data=None):
    return JsonResponse({
        'code': code,
        'message': message,
        'data': data or {}
    }, status=401)